package cn.edu.jcu.kyle.gintama.OurUtil;

import cn.edu.jcu.kyle.gintama.DbUtil;
import cn.edu.jcu.kyle.gintama.Main;
import cn.edu.jcu.kyle.gintama.data.BVideo.BVideoData;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.stage.Stage;

import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Objects;

public class BilibiliVideo {
    private static final String url = "https://qqlykm.cn/api/bilibili/get?key=3GqKUEBnQf03I2TRDuvaCJ2uzV&id=";

    private static String title;         //标题

    private static String pic;           //封面图

    private static String des;          //	简介

    private static String ownername;     //	发布者名称

    private static String ownerface;     //	发布者头像

    private static long view;          //	播放量

    private static int danmaku;       //	弹幕数量

    private static int reply;         //评论数

    private static int favorite;      //收藏数

    private static int coin;          //投币数量

    private static int share;         //转发数量

    private static int lk;          //点赞数

    private static String time;          //视频发布时间

    private static String videourl;      //视频解析URL

    private static String bvid;          //BV号
    private static Connection conn = null;
    private static ResultSet resultSet = null;
    private static final SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");

    public static void Query(String _bivd) {
        createTable();
        //输入BV名为空
        if (Objects.equals(_bivd, "")) {
            Alert alert = new Alert(Alert.AlertType.WARNING);       //弹出警告窗口
            alert.setTitle("警告窗口");
            alert.setHeaderText("输入为空！");
            alert.showAndWait();
            return;
        }
        if (queryInSQL(_bivd)) {
            showInDb(_bivd);
        } else {
            //发起http请求
            String str = HttpUtil.get(url + _bivd);
            //把返回的json转成javaBean
            BVideoData data = JSONUtil.toBean(str, BVideoData.class);
            //如果返回的json里显示请求失败
            if (!data.getSuccess()) {
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setTitle("请求失败");
                alert.setHeaderText("获取失败！");
                alert.setContentText("请检查是否是接口调用次数达到限制或网络连接是否畅通");
                alert.showAndWait();
                return;
            } else if (data.getData().getBvid() == null) {     //如果返回的json里数据为null，说明输入有误
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setTitle("警告窗口");
                alert.setHeaderText("未找到查找的视频");
                alert.setContentText("输入错误");
                alert.showAndWait();
                return;
            }
            writein(data);
            show();
            wINdb();
        }
    }

    private static boolean queryInSQL(String _bvid) {//查询搜索数据是否在数据库里存在
        try {
            conn = DbUtil.getMySQLConnection("jdbc:mysql://localhost:3306/gintama?useUnicode=utf8&useSSL=false");
            String str = "select * from BVideoData where Bvid='" + _bvid + "'";
            resultSet = DbUtil.executeQuery(conn, str);
            //判断是否存在
            return resultSet.next();
        } catch (Exception e) {
            System.out.println("报错");
            e.printStackTrace();
            return false;
        }
    }

    private static void showInDb(String _title) {//展示数据库里的数据
        ListView<String> listViewDb = new ListView<>();   //创建一个列表控件
        ObservableList<String> dataList = null;
        try {
            dataList = FXCollections.observableArrayList(
                    resultSet.getString("Bvid") +
                            "," +
                            resultSet.getString("Title") +
                            "视频的数据",
                    "封面图：" + resultSet.getString("Pic"),
                    "简介：" + resultSet.getString("Des"),
                    "发布者名称：" + resultSet.getString("Ownername"),
                    "发布者头像：" + resultSet.getString("Ownerface"),
                    "播放量：" + resultSet.getString("View"),
                    "弹幕数量：" + resultSet.getString("Danmaku"),
                    "评论数：" + resultSet.getString("Reply"),
                    "收藏数：" + resultSet.getString("Favorite"),
                    "投币数量：" + resultSet.getString("Coin"),
                    "转发数量：" + resultSet.getString("Share"),
                    "点赞数：" + resultSet.getString("lk"),
                    "视频发布时间：" + resultSet.getString("Time"),
                    "视频解析URL：" + resultSet.getString("Videourl"),
                    "BV号" + resultSet.getString("Bvid"),
                    "");
        } catch (Exception e) {
            e.printStackTrace();
            AlertWindow.getWindow("警告！发生错误！");
            System.exit(-1);
        }
        listViewDb.setItems(dataList);
        Stage stageDb = new Stage();
        stageDb.setTitle("数据库中" + _title + "的视频数据");
        stageDb.getIcons().add(new Image(Objects.requireNonNull(Main.class.getResource("img/bilibili.png")).toExternalForm()));  //新窗口图标
        stageDb.setHeight(250);
        stageDb.setWidth(300);
        stageDb.setScene(new Scene(listViewDb));
        stageDb.show();
    }

    //构造函数
    static void writein(BVideoData data) {
        title = data.getData().getTitle();
        pic = data.getData().getPic();
        des = data.getData().getDesc();
        ownername = data.getData().getOwnername();
        ownerface = data.getData().getOwnerface();
        view = data.getData().getView();
        danmaku = data.getData().getDanmaku();
        reply = data.getData().getReply();
        favorite = data.getData().getFavorite();
        coin = data.getData().getCoin();
        share = data.getData().getShare();
        lk = data.getData().getLike();
        time = sf.format(data.getData().getDate());
        videourl = data.getData().getVideourl();
        bvid = data.getData().getBvid();
    }

    private static void show() {//展示当前搜索数据
        ListView<String> listView = new ListView<>();   //创建一个列表控件
        ObservableList<String> dataList = FXCollections.observableArrayList(title,
                "封面图：" + pic,
                "简介：" + des,
                "发布者名称：" + ownername,
                "发布者头像：" + ownerface,
                "播放量：" + view,
                "弹幕数量：" + danmaku,
                "评论数：" + reply,
                "收藏数：" + favorite,
                "投币数量：" + coin,
                "点赞数：" + share,
                "视频发布时间：" + time,
                "视频解析URL：" + videourl
        );       //列表显示数据
        listView.setItems(dataList);
        Stage stage = new Stage();              //创建一个新窗口
        stage.setTitle(title + "视频信息"); //新窗口的标题
        stage.getIcons().add(new Image(Objects.requireNonNull(Main.class.getResource("img/bilibili.png")).toExternalForm()));  //新窗口图标
        stage.setHeight(250);                   //新窗口高度
        stage.setWidth(300);                    //新窗口宽度
        stage.setScene(new Scene(listView));    //这个窗口里边装着上边那个列表控件
        stage.show();                           //弹出新窗口
    }

    private static void wINdb() {//写入数据库
        try {
            conn = DbUtil.getMySQLConnection("jdbc:mysql://localhost:3306/gintama?useUnicode=utf8&useSSL=false");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String insertSQL = "insert into BVideoData (Bvid, Title, Pic, Des, Ownername, Ownerface, View, Danmaku, Reply, Favorite, Coin, Share, lk, Time, Videourl) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        Object[] paramsInsert = {bvid, title, pic, des, ownername, ownerface, view, danmaku, reply, favorite, coin, share, lk, time, videourl};
        DbUtil.executeUpdate(conn, insertSQL, paramsInsert);
    }

    private static void createTable() {
        String createTable = """
                create table if not exists gintama.BVideoData
                (
                    Bvid   varchar(255) not null comment 'BV号',
                    Title     varchar(255) not null comment '标题',
                    Pic   varchar(255) not null comment '封面图',
                    Des    varchar(255) not null comment '简介',
                    Ownername varchar(255) not null comment '发布者名称',
                    Ownerface varchar(255) not null comment '发布者头像',
                    View varchar(255) not null comment '播放量',
                    Danmaku varchar(255) not null comment '弹幕数量',
                    Reply varchar(255) not null comment '评论数',
                    Favorite varchar(255) not null comment '收藏数',
                    Coin varchar(255) not null comment '投币数量',
                    Share varchar(255) not null comment '转发数量',
                    lk varchar(255) not null comment '点赞数',
                    Time varchar(255) comment '视频发布时间',
                    Videourl varchar(600) not null comment '视频解析URL',
                    constraint BVideoData_pk
                        primary key (Bvid)
                )""";
        try {
            conn = DbUtil.getMySQLConnection("jdbc:mysql://localhost:3306/gintama?useUnicode=utf8&useSSL=false");
            DbUtil.executeUpdate(conn, createTable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}